package rensoft.portfolio.client.view.pages;

import static com.google.gwt.query.client.GQuery.$;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Cursor;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.query.client.css.CSS;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;

import java.util.Iterator;

import rensoft.gwt.client.view.View;
import rensoft.portfolio.client.model.titles.Page;
import rensoft.portfolio.client.model.titles.Titles;
import rensoft.portfolio.client.model.titles.Titles.TitleState;
import rensoft.portfolio.client.view.workslides.WorksSlidesWidget;

public class PageView extends View<FlowPanel> implements HasWidgets {

  static Binder uiBinder = GWT.create(Binder.class);

  @UiField(provided = true)
  ImageResource image;

  @UiField(provided = true)
  String text;

  @UiField
  Image imageWidget;
  private final Page page;

  @UiConstructor
  public PageView(Page page) {
    super.initialize(page);
    this.page = page;
    text = page.getText();
    image = page.getImage();
    initWidget(uiBinder.createAndBindUi(this));
    if (get(Titles.class).getState() == TitleState.products) {
      $(imageWidget).css(CSS.CURSOR.with(Cursor.POINTER));
      imageWidget.addClickHandler(new ClickHandler() {
        public void onClick(ClickEvent event) {
          onProductImageClick();
        }
      });
    }
  }

  public void add(IsWidget w) {
    add(w.asWidget());
  }

  public void add(Widget w) {
    widget().add(w);
  }

  public void clear() {
    widget().clear();
  }

  public Iterator<Widget> iterator() {
    return widget().iterator();
  }

  public boolean remove(Widget w) {
    return widget().remove(w);
  }

  private void onProductImageClick() {
    get(WorksSlidesWidget.class).show(page);
    get(Titles.class).open(TitleState.closed);
    get(WorksSlidesWidget.class).pause();
  }

  interface Binder extends UiBinder<FlowPanel, PageView> {}
}
